var async = require('async');
var AV = require('leanengine');

//用户优惠券表
var UserCoupon = AV.Object.extend('UserCoupon');
//优惠券
var Coupons = AV.Object.extend('Coupons');
var CouponsFlow = AV.Object.extend('CouponsFlow');
module.exports = {
    /**
     * 发放优惠券
     * @param uid    用户id
     * @param couponsId   优惠券id
     * @param validityPeriod  优惠券有效期
     * @returns {*|promise}
     */
    giveCoupons:function(uid,couponsId,validityPeriod){
        validityPeriod = parseInt(validityPeriod) || 7 ;
        var timestamp = Date.parse(new Date(new Date().setHours(23,59,59)));
        var startTime = Date.parse(new Date());

        var promise = new AV.Promise();
        async.waterfall([
            //判断优惠券是否存在
            function(callback){
                var query = new AV.Query(Coupons);
                query.get(couponsId+"").then(function(res){
                    if(res){
                        callback(null,res);
                    }else{
                        callback({code:1047,msg:"优惠券未设置"});
                    }
                }).catch(function(err){
                    callback({code:1047,msg:"优惠券未设置"});
                });
            },
            //发放优惠券
            function(res,callback){
                var takeCoupon = new UserCoupon();
                var endVaildTime=String(timestamp+validityPeriod*3600*24*1000);
                var newCoupon={'uid':uid,'cid':res.get("batchNo"),GiveTime:new Date(),'validityEndPeriod':endVaildTime,'used':0,'status':1,coupon:res.attributes,validityStartPeriod:String(startTime)};
                takeCoupon.save(newCoupon).then(function(res){
                    callback(null,{code:0,msg:"发放成功",res:res});
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /**
     * 记录优惠券发放流水
     * @param uid
     * @param couponsId
     * @returns {*|promise}
     */
    couponsFlow:function(uid,couponsId){
        var promise = new AV.Promise();
        var flow = new CouponsFlow();
        flow.set('uid',uid+"");
        flow.set('couponsId',couponsId+"");
        flow.save().then(function(){
            promise.resolve({code:0});
        }).catch(function(err){
            promise.reject(err);
        });
        return promise;
    },
    countCouponsFlow:function(uid,couponsId){
        var promise = new AV.Promise();
        var query = new AV.Query(CouponsFlow);
        query.equalTo('uid',uid+"");
        query.equalTo('couponsId',couponsId+"");
        query.count().then(function(count){
            promise.resolve({code:0,count:count});
        }).catch(function(err){
            promise.reject(err);
        });
        return promise;
    }
}